/**
 * http配置
 */

import axios from 'axios';
import { MessageBox, Message } from 'element-ui';
import router from '../router';
import { downloadFile } from '@/common/util';

function buildHeader(): { [key: string]: string } {
    return {
        'Content-Type': 'application/json;charset=UTF-8;multipart/form-data'
    };
}

export let ax = axios.create({
    baseURL: host(),
    headers: buildHeader(),
    timeout: 300000,
    responseType: 'json',
    withCredentials: false,
    transformRequest: [
        function (data) {
            if (data instanceof FormData) return data;
            return JSON.stringify(data);
        }
    ],
    transformResponse: [
        function (data) {
            if (data) {
                var data = typeof data == 'object' ? data : JSON.parse(data); //兼容IE
                return data;
            } else {
                let msg = 'Unknow Error';
                throw new Error(msg);
            }
        }
    ],
    // `onUploadProgress`允许处理上传的进度事件
    onUploadProgress: function (progressEvent) {
        // 使用本地 progress 事件做任何你想要做的
    },
    // `onDownloadProgress`允许处理下载的进度事件
    onDownloadProgress: function (progressEvent) {
        // Do whatever you want with the native progress event
    }
});

export function host(): string {
    if (window.location.hostname == 'localhost' || window.location.hostname.indexOf('192.168') > -1) {
        return '/'; //代理
        // return 'http://192.168.18.218:5000/';
    } else {
        return '/';
    }
}

// http request 拦截器
ax.interceptors.request.use(
    config => {
        if (sessionStorage.getItem('jwtToken')) {
            config.headers.Authorization = `Bearer ${sessionStorage.getItem('jwtToken')}`;
        }
        return config;
    },
    err => {
        // return Promise.reject(err);
    }
);

// http response 拦截器
ax.interceptors.response.use(
    response => {
        if (!response.data.success) {
            switch (response.data.errorCode) {
                case '10002': //token失效，没有访问权限
                    sessionStorage.clear();
                    location.reload();
                    router.push('/login');
                    break;
                case '30003': //未登录
                    MessageBox.alert('未登录状态,请重新登录！', '提示', {
                        confirmButtonText: '确定',
                        type: 'warning',
                        callback: action => {
                            MessageBox.close();
                            sessionStorage.clear();
                            location.reload();
                            router.push('/login');
                        }
                    });

                    break;
                case '30004': //用户注销
                    MessageBox.alert('用户注销,请重新登录!', '提示', {
                        confirmButtonText: '确定',
                        type: 'warning',
                        callback: action => {
                            MessageBox.close();
                            sessionStorage.clear();
                            location.reload();
                            router.push('/login');
                        }
                    });
                    break;
                case '30005': //在别处登录
                    MessageBox.alert('用户在别处登录!', '提示', {
                        confirmButtonText: '确定',
                        type: 'warning',
                        callback: action => {
                            MessageBox.close();
                            sessionStorage.clear();
                            location.reload();
                            router.push('/login');
                        }
                    });
                    break;
                case '30006': //在别处登录
                    MessageBox.alert('用户在别处登录!', '提示', {
                        confirmButtonText: '确定',
                        type: 'warning',
                        callback: action => {
                            MessageBox.close();
                            sessionStorage.clear();
                            location.reload();
                            router.push('/login');
                        }
                    });
                    break;
                case '40007': // 开户行查询特别处理[不支持或错误的银行卡号]
                    return Promise.resolve(response.data);
                default:
                    return Promise.reject(response.data.errorMessage);
            }

        } else {
            return Promise.resolve(response.data);
        }
    },
    error => {
        if (error.code === 'ECONNABORTED') {
            MessageBox.alert('接口超时！', '提示', {
                confirmButtonText: '确定',
                callback: action => {
                    MessageBox.close();
                }
            });
        }
        if (error.response) {
            switch (error.response.status) {
                case 502:
                    MessageBox.alert('后台发布中，请稍候！', '提示', {
                        confirmButtonText: '确定',
                        callback: action => {
                            MessageBox.close();
                        }
                    });
                    break;
            }
        }
    }
);

/* 手动取消请求的不显示报错 */
function handleError(err) {
    // 如果是手动取消的请求，不显示错误信息
    console.log('handleError1', err);
    MessageBox.alert(`${err}`, '提示', {
        confirmButtonText: '确定',
        type: 'warning',
        callback: action => {
            MessageBox.close();
        }
    });
}

/* GET  */
export function Get<T>(url, data): Promise<any> {
    // `params`是要与请求一起发送的URL参数
    // 必须是纯对象或URLSearchParams对象
    return ax
        .get(url, {
            params: data
        })
        .then(res => {
            return res.data ? res.data : res;
        })
        .catch(err => {
            handleError(err);
            throw err;
        });
}

//下载excel
export function Download<T>(url, data): Promise<any> {
    return axios({
        baseURL: host(),
        url: url,
        params: data,
        headers: { Authorization: `Bearer ${sessionStorage.getItem('jwtToken')}` },
        method: 'get',
        responseType: 'blob' //二进制流
    })
        .then(res => {
            downloadFile(res);
        })
        .catch(err => {
            handleError('导出失败');
        });
    function ab2str(u, f) {
        var b = new Blob([u]);
        var r = new FileReader();
        r.readAsText(b, 'utf-8');
        r.onload = function () { if (f) f.call(null, r.result) }
    }
}

//上传流文件
export function Import<T>(url, data): Promise<any> {
    return ax
        .post(url, data, {
            method: 'post',
            headers: { 'Content-Type': 'multipart/form-data' }
        })
        .then(res => {
            return res.data ? res.data : res;
        })
        .catch(err => {
            handleError(err);
            throw err;
        });
}

/* POST */
export function Post<T>(url, data): Promise<any> {
    return ax
        .post(url, data)
        .then(res => {
            return res.data ? res.data : res;
        })
        .catch(err => {
            handleError(err);
            throw err;
        });
}
/* PUT */
export function Put<T>(url, data): Promise<any> {
    return ax
        .put(url, data)
        .then(res => {
            return res.data ? res.data : res;
        })
        .catch(err => {
            handleError(err);
            throw err;
        });
}
/* PATCH */
export function Patch<T>(url, data): Promise<any> {
    return ax
        .patch(url, data)
        .then(res => {
            return res.data ? res.data : res;
        })
        .catch(err => {
            handleError(err);
            throw err;
        });
}
/* DELETE */
export function Delete<T>(url, data): Promise<any> {
    return ax
        .delete(url, data)
        .then(res => {
            return res.data ? res.data : res;
        })
        .catch(err => {
            handleError(err);
            throw err;
        });
}
